package spring.cloud.eurekaclientproduct.collapser;

import com.netflix.hystrix.*;
import spring.cloud.eurekaclientproduct.cmd.UserFindCommand;
import spring.cloud.eurekaclientproduct.service.UserFacade;
import com.spring.cloud.commonutils.vo.UserInfo;
import com.spring.cloud.commonutils.vo.ResultMessage;
import java.util.Collection;
import java.util.List;

public class UserHystrixCollapser extends HystrixCollapser<List<UserInfo>,UserInfo,Long> {

    private UserFacade userFacade;
    private Long id;

    public UserHystrixCollapser(UserFacade userFacade, Long id) {
        super(Setter.withCollapserKey(HystrixCollapserKey.Factory.asKey("userGroup"))
                .andScope(Scope.REQUEST).andCollapserPropertiesDefaults(HystrixCollapserProperties.Setter()
                        //方法合并的时间戳
                .withTimerDelayInMilliseconds(50)
                        //请求缓存是否启用
//                        .withRequestCacheEnabled(true)
                        //合并最大请求数
                        .withMaxRequestsInBatch(3)));
        this.userFacade = userFacade;
        this.id = id;
    }

    @Override
    public Long getRequestArgument() {
        return id;
    }

    @Override       //创建命令
    protected HystrixCommand<List<UserInfo>> createCommand(
            Collection<CollapsedRequest<UserInfo, Long>> requests) {
        //从批量请求中获取所有参数
        Long[] idArr = new Long[requests.size()];
        int index = 0;
        for(CollapsedRequest<UserInfo, Long> request:requests){
            idArr[index] = request.getArgument();
            index++;
        }
        UserFindCommand ufc = new UserFindCommand(userFacade,idArr);
        return ufc;
    }

    @Override                               //批量的结果
    protected void mapResponseToRequests(List<UserInfo> batchResponse,      //批量的请求
                                         Collection<CollapsedRequest<UserInfo, Long>> requests) {
        //将批量的结果分发到批量对应的请求上
        int idx = 0;
        for(CollapsedRequest<UserInfo, Long> request:requests){
            request.setResponse(batchResponse.get(idx));
            idx++;
        }
    }
}
